﻿using HPSocketCS;
using McsUtility;
using McsUtility.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NodeServer.Common
{
    public partial class TcpForwardServer
    {
        /// <summary>
        /// 刷新钱包矿池信息
        /// </summary>
        public HandleResult MinerManagerGetCurrencysInfo(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                List<CurrencysModel> result = MCSSQL.DBUtility.DAL.GetCurrencys(extra.UserID);
                var response = ProtocolHelper.WritePackage<List<CurrencysModel>>(ProtoType.NodeServerManagerGetCurrencysInfo, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [刷新钱包矿池信息]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetCurrencysInfo>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 添加钱包
        /// </summary>
        public HandleResult MinerManagerAddWallets(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WalletsModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.WalletsRequest(1, 0, extra.UserID, wm.ID, wm.Address, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerAddWallets, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [添加钱包]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerAddWallets>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 添加矿池
        /// </summary>
        public HandleResult MinerManagerAddOrePools(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WalletsModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.WalletsRequest(2, 0, extra.UserID, wm.ID, wm.Address, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerAddOrePools, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [添加矿池]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerAddOrePools>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 删除钱包
        /// </summary>
        public HandleResult MinerManagerDelWallets(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WalletsModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.WalletsRequest(3, wm.ID, extra.UserID);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerDelWallets, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [删除钱包]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerDelWallets>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 删除矿池
        /// </summary>
        public HandleResult MinerManagerDelOrePools(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WalletsModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.WalletsRequest(4, wm.ID, extra.UserID);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerDelOrePools, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [删除矿池]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerDelOrePools>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 修改钱包
        /// </summary>
        public HandleResult MinerManagerModifyWallets(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WalletsModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.WalletsRequest(5, wm.ID, extra.UserID, 0, wm.Address, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerModifyWallets, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [修改钱包]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerModifyWallets>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 修改矿池
        /// </summary>
        public HandleResult MinerManagerModifyOrePools(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WalletsModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.WalletsRequest(6, wm.ID, extra.UserID, 0, wm.Address, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerModifyOrePools, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [修改矿池]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerModifyOrePools>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 获取矿工
        /// </summary>
        public HandleResult MinerManagerGetMiners(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<MinersRequestModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.GetMiners(extra.UserID, wm.State, wm.Currency, wm.OrePool, wm.Wallet, wm.PageIndex, wm.PageRows);
                byte[] responsebody = ProtoBufHelper.SerializeBytes<MinersResponseModel>((MinersResponseModel)result.data);
                var response = ProtocolHelper.WritePackage(ProtoType.NodeServerManagerGetMiners, responsebody);
                bool a=server.Send(connId, response, response.Length);
                //logger.Debug(connId + ">" + a.ToString() + ">NodeServerManagerGetMiners>" + TomNet.Utility.Data.JsonHelper.ToJson(result));
                //AddMsg(" > [获取矿工]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetMiners>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 获取单个矿工
        /// </summary>
        public HandleResult MinerManagerGetMinerModel(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var MinerID = ProtocolHelper.ReadPackageBody<int>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.GetMinerModel(MinerID);
                byte[] responsebody = ProtoBufHelper.SerializeBytes<MinersModel>((MinersModel)result.data);
                var response = ProtocolHelper.WritePackage(ProtoType.NodeServerManagerGetMinerModel, responsebody);
                bool a=server.Send(connId, response, response.Length);
                //logger.Debug(connId + ">" + a.ToString() + ">NodeServerManagerGetMiners>" + TomNet.Utility.Data.JsonHelper.ToJson(result));
                //AddMsg(" > [获取矿工]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetMiners>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 修改矿工挖矿信息
        /// </summary>
        public HandleResult MinerManagerModifyOrePoolUrl(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var responseComm = ProtocolHelper.WritePackage(ProtoType.MinerManagerModifyOrePoolUrlCommServer, body);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                //AddMsg(" > [修改矿工挖矿信息]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerModifyOrePoolUrl>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 批量修改矿工挖矿信息
        /// </summary>
        public HandleResult MinerManagerModifyBatch(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var responseComm = ProtocolHelper.WritePackage(ProtoType.MinerManagerModifyBatchCommServer, body);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                //AddMsg(" > [批量修改矿工挖矿信息]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerModifyBatch>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 让矿工开始挖矿
        /// </summary>
        public HandleResult MinerManagerStartMining(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var responseComm = ProtocolHelper.WritePackage(ProtoType.MinerManagerStartMiningCommServer, body);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                //AddMsg(" > [让矿工开始挖矿]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerStartMining>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 让矿工停止挖矿
        /// </summary>
        public HandleResult MinerManagerEndMining(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var responseComm = ProtocolHelper.WritePackage(ProtoType.MinerManagerEndMiningCommServer, body);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                //AddMsg(" > [让矿工停止挖矿]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerEndMining>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 矿工重启电脑
        /// </summary>
        public HandleResult MinerManagerReset(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var responseComm = ProtocolHelper.WritePackage(ProtoType.MinerManagerResetCommServer, body);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                //AddMsg(" > [矿工重启电脑]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerReset>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 开始挖矿
        /// </summary>
        public HandleResult MinerClientStartMining(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var a = ProtocolHelper.ReadPackageBody(body);
                var wm = ProtocolHelper.ReadPackageBody<MinersModel>(body);
                MCSSQL.DBUtility.DAL.MinersRequest(4, extra.MinerID, extra.UserID, wm.MacAddress, wm.AutoName, wm.AutoRun, wm.AutoUpdate, wm.MinerName, 2, wm.FirstCoin, wm.SecondCoin, wm.FirstPool, wm.SecondPool, wm.FirstWallet, wm.SecondWallet, wm.MinFan, wm.MaxFan, wm.Dcri, wm.Second, wm.AdvParams, wm.BackupPool, wm.MinTemp, wm.MaxTemp, wm.Eres, wm.MinSpeed, (int)wm.HighTempStrategy, wm.HighTempWarn, wm.LowStrengthWarn, (int)wm.CoreType);
                wm.ID = extra.MinerID;
                wm.UserID = extra.UserID;
                var responseComm = ProtocolHelper.WritePackage<MinersModel>(ProtoType.MinerClientStartMiningToCommServer, wm);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                logger.Info("MinerClientStartMining>" + connId);
                MCSSQL.DBUtility.DAL.AddMinerLog(extra.MinerID, "开始挖矿！");

                //AddMsg(" > [开始挖矿]");
            }
            catch (Exception e)
            {

                logger.Error("MinerClientStartMining>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 停止挖矿
        /// </summary>
        public HandleResult MinerClientStopMining(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                MCSSQL.DBUtility.DAL.MinersRequest(5, extra.MinerID, extra.UserID);
                MinerCloseModel m = new MinerCloseModel();
                m.connID = connId.ToInt32();
                m.MinerID = extra.MinerID;
                m.MinerName = extra.MinerName;
                m.UserID = extra.UserID;
                var responseComm = ProtocolHelper.WritePackage<MinerCloseModel>(ProtoType.MinerClientEndMiningToCommServer, m);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                //logger.Debug("MinerClientStopMining>" + m.connID + ">" + m.MinerID + ">" + m.MinerName + ">" + m.UserID);
                //AddMsg(" > [停止挖矿]");
                MCSSQL.DBUtility.DAL.AddMinerLog(extra.MinerID, "停止挖矿！");

            }
            catch (Exception e)
            {

                logger.Error("MinerClientStopMining>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 删除矿工
        /// </summary>
        public HandleResult MinerManagerDelMiner(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var m = ProtocolHelper.ReadPackageBody<int[]>(body);
                foreach (var item in m)
                {
                    MCSSQL.DBUtility.DAL.MinersRequest(2, item, extra.UserID);
                }

                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerMinerManagerDelMiner, new ResultModel() { success = true, message = "成功", data = "" });
                server.Send(connId, response, response.Length);
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerDelMiner>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 矿工同步数据
        /// </summary>
        public HandleResult MinerClientSendData(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody(body);
                redisClient.StringSet(extra.MinerID.ToString(), wm, new TimeSpan(0, 1, 0));
                string calculatingtime = DateTime.Now.ToString("yyyy-MM-dd HH:00:00");
                if (calculatingtime != extra.CalculatingTime.ToString("yyyy-MM-dd HH:00:00"))
                {
                    MinerHashrate infoRedis = TomNet.Utility.Data.JsonHelper.FromJson<MinerHashrate>(wm);
                    //List<string> ta = infoRedis.Ta.ConvertListString(';');
                    string [] ta = infoRedis.Ta.Split(new char[] { ';' });
                    decimal calculating = ta[0].ConvertDecimal();
                    if (calculating > 0 && Convert.ToInt32(MCSSQL.DBUtility.DbHelperSQL.GetSingle("select count(*) from MinerCalculatings where MinerID=" + extra.MinerID + " and Currencys=(select FirstCoin from Miners where Miners.ID=" + extra.MinerID + ") and CalculatingDay='" + calculatingtime + "'")) == 0)
                    {
                        MCSSQL.DBUtility.DbHelperSQL.ExecuteSql("INSERT INTO MinerCalculatings(StaffID,UserID,MinerID,Currencys, Calculating, CalculatingDay) VALUES (isnull((select StaffID from Users where Users.ID=" + extra.UserID + "),0)," + extra.UserID + "," + extra.MinerID + ",(select FirstCoin from Miners where Miners.ID=" + extra.MinerID + ")," + calculating + ",'" + calculatingtime + "')");
                        extra.CalculatingTime = DateTime.Now;
                    }
                }

            }
            catch (Exception e)
            {

                logger.Error("MinerClientSendData>" + e.Message);
            }
            //AddMsg(" > [矿工同步数据]");
            return HandleResult.Ok;
        }
        /// <summary>
        /// 管理端获实时数据
        /// </summary>
        public HandleResult MinerManagerGetRedisData(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<List<int>>(body);
                List<RedisDataModel> l = new List<RedisDataModel>();
                foreach (var item in wm)
                {
                    RedisDataModel m = new RedisDataModel();
                    m.MinerID = item;
                    m.RedisData = redisClient.StringGet(item.ToString());
                    if (m.RedisData==null)
                    {
                        m.RedisData = "";
                    }
                    l.Add(m);
                }
                var response = ProtocolHelper.WritePackage<List<RedisDataModel>>(ProtoType.NodeServerMinerManagerGetRedisData, l);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [管理端获实时数据]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetRedisData>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 矿工登录
        /// </summary>
        public HandleResult MinerClientLogin(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                if (this.ConnectionCount > this.MaxConnectionCount)
                {
                    //连接数超上限

                    var responseComm = ProtocolHelper.WritePackage<int>(ProtoType.GetNodeServerCommServer, connId.ToInt32());
                    if (!agent.Send(connIdForAgent, responseComm, responseComm.Length))
                    {
                        if (!agent.Send(connIdForAgent, responseComm, responseComm.Length))
                        {
                            return HandleResult.Error;
                        }
                    }
                    return HandleResult.Ok;
                }
                extra.ClientType = ClientType.MinerClient;
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<LoginModel>(body);
                if (String.IsNullOrEmpty(lm.Version))
                {
                    lm.Version = "";
                }
                ResultModel result = MCSSQL.DBUtility.DAL.Login(1, lm.LoginName, lm.LoginPass);
                if (result.success)
                {
                    try
                    {
                        extra.Activated = true;
                        extra.UserID = ((LoginResultModel)result.data).UserID;
                        extra.Name = ((LoginResultModel)result.data).Name;
                        ResultModel mr = MCSSQL.DBUtility.DAL.MinersRequest(1, 0, ((LoginResultModel)result.data).UserID, lm.MacAddress, false, false, false, lm.Name, 0, "", "", "", "", "", "", "", "", "", false, "", "", "", "", "", "", 0, false, false, 0, lm.Version);
                        extra.MinerID = (int)mr.data;
                        extra.MinerName = lm.Name;
                        extra.HeartbeatTime = DateTime.Now;
                        result.data = "";
                        MCSSQL.DBUtility.DAL.AddMinerLog(extra.MinerID, "上线！");
                        redisClientD1.StringSet("H" + extra.MinerID.ToString(), "H" + extra.MinerID.ToString(), new TimeSpan(0, 0, 30));
                    }
                    catch (Exception e)
                    {
                        logger.Error("Login写库：" + e.Message);
                    }
                }
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerClientLogin, result);
                if (server.Send(connId, response, response.Length))
                {
                    string a = "1";
                    try
                    {
                        LoginResultForCommServerModel m = new LoginResultForCommServerModel();
                        m.ClientType = ClientType.MinerClient;
                        m.connID = connId.ToInt32();
                        m.Name = extra.Name;
                        m.UserID = extra.UserID;
                        m.MinerID = extra.MinerID;
                        m.MinerName = extra.MinerName;
                        var responseComm = ProtocolHelper.WritePackage<LoginResultForCommServerModel>(ProtoType.MinerLoginCommServer, m);
                        a = "2";
                        agent.Send(connIdForAgent, responseComm, responseComm.Length);
                    }
                    catch (Exception e)
                    {
                        logger.Error("Login转发" + a + "：" + e.Message);
                    }
                }
                else
                {
                    return HandleResult.Error;
                }
                minersConnID.AddOrUpdate(extra.MinerID, connId.ToInt32(), (tKey, existingVal) => { return connId.ToInt32(); });
                //AddMsg(" > [登录成功]");

            }
            catch (Exception ex)
            {

                logger.Error("MinerClientLogin>" + ex.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 管理端登录
        /// </summary>
        public HandleResult MinerManagerLogin(IntPtr connId, byte[] body, ConnExtraData extra, ProtoType proto)
        {
            try
            {
                if (this.ConnectionCount > this.MaxConnectionCount)
                {
                    //连接数超上限
                    var responseComm = ProtocolHelper.WritePackage<int>(ProtoType.GetNodeServerCommServer, connId.ToInt32());
                    if (!agent.Send(connIdForAgent, responseComm, responseComm.Length))
                    {
                        if (!agent.Send(connIdForAgent, responseComm, responseComm.Length))
                        {
                            return HandleResult.Error;
                        }
                    }
                    logger.Debug("超上限"+connId);
                    return HandleResult.Ok;
                }
                if (proto == ProtoType.MinerManagerLogin)
                {
                    extra.ClientType = ClientType.AdminClient;
                }
                else
                {
                    extra.ClientType = ClientType.AppClient;
                }
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<LoginModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.Login(1, lm.LoginName, lm.LoginPass);
                if (result.success)
                {
                    extra.Activated = true;
                    extra.UserID = ((LoginResultModel)result.data).UserID;
                }
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerLogin, result);
                if (server.Send(connId, response, response.Length))
                {
                    LoginResultForCommServerModel m = new LoginResultForCommServerModel();
                    m.ClientType = ClientType.AdminClient;
                    m.connID = connId.ToInt32();
                    m.Name = ((LoginResultModel)result.data).Name;
                    m.UserID = ((LoginResultModel)result.data).UserID;
                    var responseComm = ProtocolHelper.WritePackage<LoginResultForCommServerModel>(ProtoType.MinerLoginCommServer, m);
                    if (!agent.Send(connIdForAgent, responseComm, responseComm.Length))
                    {
                        return HandleResult.Error;
                    }
                }
                else
                {
                    return HandleResult.Error;
                }
                //AddMsg(" > [登录成功]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerLogin>" + e.Message);
            }
            logger.Info("MinerManagerLogin>" + connId);

            return HandleResult.Ok;
        }
        /// <summary>
        /// 管理端申请注册验证码
        /// </summary>
        public HandleResult MinerManagerGetRegSmsCode(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                extra.ClientType = ClientType.MinerClient;
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<LoginModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.Login(2, lm.LoginName);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerGetRegSmsCode, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [验证码发送成功]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetRegSmsCode>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 管理端提交注册信息
        /// </summary>
        public HandleResult MinerManagerReg(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                extra.ClientType = ClientType.MinerClient;
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<RegModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.Login(4, lm.LoginName, lm.LoginPass, lm.SMSCode, lm.Name, lm.Sex, lm.CardID, lm.PassQuestion1, lm.PassAnswer1, lm.PassQuestion2, lm.PassAnswer2, lm.PassQuestion3, lm.PassAnswer3);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerReg, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [注册成功]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerReg>" + e.Message);
            }
            return HandleResult.Ok;
        }

        /// <summary>
        /// 管理端申请注册验证码
        /// </summary>
        public HandleResult MinerManagerGetRePassSmsCode(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                extra.ClientType = ClientType.MinerClient;
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<LoginModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.Login(3, lm.LoginName);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerGetRePassSmsCode, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [验证码发送成功]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetRePassSmsCode>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 管理端提交修改密码
        /// </summary>
        public HandleResult MinerManagerRePass(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                extra.ClientType = ClientType.MinerClient;
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<RegModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.Login(5, lm.LoginName, lm.LoginPass, lm.SMSCode, lm.Name, lm.Sex, lm.CardID, lm.PassQuestion1, lm.PassAnswer1, lm.PassQuestion2, lm.PassAnswer2, lm.PassQuestion3, lm.PassAnswer3);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerRePass, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [注册成功]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerRePass>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 管理端提交修改业务员
        /// </summary>
        public HandleResult MinerManagerReStaff(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                extra.ClientType = ClientType.MinerClient;
                //serverExtra.Set(connId, extra);
                var lm = ProtocolHelper.ReadPackageBody<RegModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.Login(6, lm.LoginName, lm.LoginPass, lm.SMSCode, lm.Name, lm.Sex, lm.CardID, lm.PassQuestion1, lm.PassAnswer1, lm.PassQuestion2, lm.PassAnswer2, lm.PassQuestion3, lm.PassAnswer3);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerMinerManagerReStaff, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [注册成功]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerRePass>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 添加备注
        /// </summary>
        public HandleResult MinerManagerAddRemark(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<RemarkModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.RemarkRequest(1, 0, extra.UserID, wm.MinerID, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerAddRemark, result);
                server.Send(connId, response, response.Length);
                //AddMsg(" > [添加钱包]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerAddRemark>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 删除备注
        /// </summary>
        public HandleResult MinerManagerDelRemark(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<RemarkModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.RemarkRequest(2, wm.ID, extra.UserID, wm.MinerID, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerDelRemark, result);
                server.Send(connId, response, response.Length);
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerDelRemark>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 修改备注
        /// </summary>
        public HandleResult MinerManagerModifyRemark(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<RemarkModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.RemarkRequest(3, wm.ID, extra.UserID, wm.MinerID, wm.Remark);
                var response = ProtocolHelper.WritePackage<ResultModel>(ProtoType.NodeServerManagerModifyRemark, result);
                server.Send(connId, response, response.Length);
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerModifyRemark>" + e.Message);
            }
            return HandleResult.Ok;
        }
        public HandleResult MinerClientWarnToNodeServer(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<WarnModel>(body);
                wm.ConnID = connId.ToInt32();
                wm.MinerID = extra.MinerID;
                wm.MinerName = extra.MinerName;
                wm.UserID = extra.UserID;
                var responseComm = ProtocolHelper.WritePackage<WarnModel>(ProtoType.NodeServerWarnToCommServer, wm);
                agent.Send(connIdForAgent, responseComm, responseComm.Length);
                MCSSQL.DBUtility.DAL.AddMinerLog(extra.MinerID, wm.WarnMessage);
            }
            catch (Exception e)
            {

                logger.Error("MinerClientWarnToNodeServer>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 心跳
        /// </summary>
        public HandleResult MinerClientHeartbeat(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                extra.HeartbeatTime = DateTime.Now;
                redisClientD1.StringSet("H"+extra.MinerID.ToString(), "H" + extra.MinerID.ToString(), new TimeSpan(0, 0, 30));
            }
            catch (Exception e)
            {

                logger.Error("MinerClientHeartbeat>" + e.Message);
            }
            return HandleResult.Ok;
        }

        public HandleResult MinerManagerGetLogs(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<MinerLogsRequestModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.GetLogs(wm.MinerID, wm.PageIndex, wm.PageRows);
                //byte[] responsebody = ProtoBufHelper.SerializeBytes<MinerLogsResponseModel>((MinerLogsResponseModel)result.data);
                var response = ProtocolHelper.WritePackage<MinerLogsResponseModel>(ProtoType.NodeServerMinerManagerGetLogs, (MinerLogsResponseModel)result.data);
                bool a = server.Send(connId, response, response.Length);
                //logger.Debug(connId + ">" + a.ToString() + ">NodeServerManagerGetMiners>" + TomNet.Utility.Data.JsonHelper.ToJson(result));
                //AddMsg(" > [获取矿工]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetLogs>" + e.Message);
            }
            return HandleResult.Ok;
        }
        public HandleResult MinerManagerGetStaffs(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                ResultModel result = MCSSQL.DBUtility.DAL.GetStaffs();
                var response = ProtocolHelper.WritePackage<List<StaffModel>>(ProtoType.NodeServerMinerManagerGetStaffs, (List<StaffModel>)result.data);
                bool a = server.Send(connId, response, response.Length);
            }
            catch (Exception e)
            {
                logger.Error("MinerManagerGetStaffs>" + e.Message);
            }
            return HandleResult.Ok;
        }
        /// <summary>
        /// 获取矿工
        /// </summary>
        public HandleResult MinerManagerGetMinersAll(IntPtr connId, byte[] body, ConnExtraData extra)
        {
            try
            {
                var wm = ProtocolHelper.ReadPackageBody<MinersRequestModel>(body);
                ResultModel result = MCSSQL.DBUtility.DAL.GetMiners(extra.UserID, wm.State, wm.Currency, wm.OrePool, wm.Wallet, 1, 1000000);
                MinersResponseModel m = new MinersResponseModel();
                m.OnLineRows = ((MinersResponseModel)result.data).OnLineRows;
                m.Rows = ((MinersResponseModel)result.data).Rows;
                m.TotalRows = ((MinersResponseModel)result.data).TotalRows;
                m.WarnRows = ((MinersResponseModel)result.data).WarnRows;
                m.Miners = new List<MinersModel>();
                while (((MinersResponseModel)result.data).Miners.Count > 0)
                {
                    m.Miners.RemoveAll(p => 1 == 1);
                    m.Miners.AddRange(((MinersResponseModel)result.data).Miners.Take(20));
                    byte[] responsebody = ProtoBufHelper.SerializeBytes<MinersResponseModel>(m);
                    var response = ProtocolHelper.WritePackage(ProtoType.NodeServerManagerGetMinersAll, responsebody);
                    bool a = server.Send(connId, response, response.Length);
                    if (((MinersResponseModel)result.data).Miners.Count>=20)
                    {
                        ((MinersResponseModel)result.data).Miners.RemoveRange(0, 20);
                    }
                    else
                    {
                        ((MinersResponseModel)result.data).Miners.RemoveRange(0, ((MinersResponseModel)result.data).Miners.Count);
                    }
                }
                //logger.Debug(connId + ">" + a.ToString() + ">NodeServerManagerGetMiners>" + TomNet.Utility.Data.JsonHelper.ToJson(result));
                //AddMsg(" > [获取矿工]");
            }
            catch (Exception e)
            {

                logger.Error("MinerManagerGetMiners>" + e.Message);
            }
            return HandleResult.Ok;
        }

    }
}
